﻿using Fleck;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace SuperX.WebSocketService.Server
{
    public class WsConnectionInfo : IDisposable
    {
        public IWebSocketConnection WebSocketConnection { get; set; }

        public string ConnectionId => WebSocketConnection.ConnectionInfo.Id.ToString();

        public bool IsConnected => WebSocketConnection != null;

        public long heartbeat { get; set; }

        public HashSet<string> SubscribeData { get; set; }

        public void Send(string sender, string Topic)
        {
            if (WebSocketConnection != null && WebSocketConnection.IsAvailable && (SubscribeData == null || SubscribeData.Contains(Topic)))
                WebSocketConnection.Send(sender);
        }

        public void Dispose()
        {
            if (WebSocketConnection != null)
            {
                WebSocketConnection.Close();
                WebSocketConnection = null;
            }
        }
    }

    public class Message<T>
    {
        public string Type { get; set; }

        public T Content { get; set; }

        public static Message<T> Convert(string value)
        {
            try
            {
                return JsonConvert.DeserializeObject<Message<T>>(value);
            }
            catch
            {
                return null;
            }
        }
    }
}